<template>
  <div style="margin-top:70px">
    <upload-excel :on-success="handleSuccess" :before-upload="beforeUpload" />
  </div>
</template>

<script>
import { formatExcelDate } from '@/utils/index'

import { importEmployees } from '@/api/employees'
export default {
  name: 'Import',
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    async  handleSuccess({ results, header }) {
      console.log(results, header)
      const data = this.transExcel(results)
      console.log('表单数据', data)
      try {
        const res = await importEmployees(data)
        this.$message.success(res.message)
        // 返回上一级
        this.$router.back()
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    transExcel(results) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      return results.map(zhObj => {
        const enObj = {}
        // 1.拿到所有的中文key
        // Object.keys()获取对象所有的属性名
        const zhKeys = Object.keys(zhObj)
        // 2.将中文key转换成英文key
        zhKeys.forEach(zhKey => {
          // 根据中文，取出对应的英文
          const enKey = mapInfo[zhKey]
          if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
            enObj[enKey] = new Date(formatExcelDate(zhObj[zhKey]))
          } else {
            // 3.拼装成英文对象
            enObj[enKey] = zhObj[zhKey]
          }
        })
        return enObj
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
